<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="handleDownLoad">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" :default-sort="{prop:'mobile',order:'ascending'}">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffPhoto"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column
            label="聘用形式"
            :formatter="formatter"
            prop="formOfEmployment"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template v-slot="scope">

              <span> {{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间" prop="correctionTime" sortable>
            <template v-slot="scope">

              <span> {{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="50%"
          @close="dialogClose"
        >

          <emp-dialog
            ref="addEmpt"
            @close="showDialog = false"
            @updata-list="updataList"
          />

        </el-dialog>
        <!-- 分配角色弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          width="50%"
        >
          <assign-role v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog = false" />

        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'
import AssignRole from './assignRole.vue'
export default {
  name: 'Employess',
  components: {
    AssignRole,
    // PageTools
    empDialog
  },
  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false,
      showRoleDialog: false, // 分配角色弹框
      roleId: ''

    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {

    // 分配角色
    setEmp(id) {
      this.roleId = id
      this.showRoleDialog = true
    },
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    // 获取员工列表
    async  getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },
    // 删除员工
    async  delEmp(id) {
      // 询问框
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击取消
      if (confirmRes === 'cancel') return this.$message('再乱点删除,把你小JJ剁了')
      // 点击确定
      // 调用删除接口
      const res = await delEmployee(id)
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      this.$message.success(res.message)
      this.getEmployeeList()
    },
    updataList() {
      this.showDialog = false
      this.getEmployeeList()
    },
    // 监听表单关闭方法
    dialogClose() {
      this.$refs.addEmpt.resetForm()
    },
    async  handleDownLoad() {
      const res = await getEmployeeList(this.query)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: excelObj.header, // 表头
          data: excelObj.data, // 具体的数据
          filename: '员工列表', // 文档的名字
          autoWidth: true, // 单元格是否自适应
          bookType: 'xlsx' // 导出的文件类型
        })
      })
    },
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 可视化表头
      const headerKeys = Object.keys(rows[0])
      // 遍历头
      const header = headerKeys.map(item => {
        return map[item]
      })

      const data = rows.map(obj => {
        // 就是将当前遍历的对象中每一项的值组成一个新的数组
        return Object.values(obj)
      })
      return { header, data }
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
